package com.yjht.system.web;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.yjht.system.model.Resource;
import com.yjht.secrity.auth.AuthUser;
import com.yjht.system.service.IResourceService;
import net.dreamlu.boot.annotation.SysLog;
import net.dreamlu.boot.result.Results;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.validation.Valid;

/**
 * <p>
 * 资源 前端控制器
 * </p>
 *
 * @author lengleng
 * @since 2018-01-29
 */
@Controller
@RequestMapping("/resource")
public class ResourceController {

	@Autowired
	private IResourceService resourceService;

	@GetMapping("/manager")
	public String manager() {
		return "system/resource/resourceList";
	}

	/**
	 * 所有的资源列表
	 */
	@PostMapping("/dataGrid")
	@ResponseBody
	public Object dataGrid() {
		Resource resource = new Resource();
		EntityWrapper<Resource> wrapper = new EntityWrapper<>(resource);
		wrapper.orderBy("seq");
		return resourceService.selectList(wrapper);
	}

	/**
	 * 查询所有的菜单
	 */
	@RequestMapping("/allMenu")
	@ResponseBody
	public Object allMenu() {
		return resourceService.findAllMenu();
	}

	/**
	 * 查询所有的资源tree
	 */
	@RequestMapping("/allTrees")
	@ResponseBody
	public Object allTree() {
		return resourceService.findAllTree();
	}

	/**
	 * 用户可见的资源
	 */
	@PostMapping("/menu")
	@ResponseBody
	public Object tree(AuthUser authUser) {
		return resourceService.findUserTree(authUser);
	}

	/**
	 * 添加页面
	 */
	@GetMapping("/addPage")
	public String addPage() {
		return "system/resource/resourceAdd";
	}

	/**
	 * 添加
	 */
	@PostMapping("/add")
	@PreAuthorize("@sec.hasPermission('resource:add')")
	@ResponseBody
	public Object add(@Valid Resource resource) {
		return Results.status(resourceService.insert(resource));
	}

	/**
	 * 删除
	 */
	@PostMapping("/delete")
	@PreAuthorize("@sec.hasPermission('resource:delete')")
	@ResponseBody
	@SysLog("删除资源")
	public Object delete(Resource resource) {
		return Results.status(resourceService.deleteById(resource));
	}

	/**
	 * 编辑页
	 */
	@GetMapping("/editPage")
	public String editPage(Model model, Long id) {
		Resource resource = resourceService.selectById(id);
		model.addAttribute("resource", resource);
		return "system/resource/resourceEdit";
	}

	/**
	 * 编辑
	 */
	@PostMapping("/edit")
	@PreAuthorize("@sec.hasPermission('resource:edit')")
	@ResponseBody
	public Object edit(@Valid Resource resource) {
		return Results.status(resourceService.updateById(resource));
	}
}
